<template>
  <div class="search-container">
    <!-- 搜索栏事件监听 -->
    <form action="/">
      <van-search v-model="searchText" show-action placeholder="请输入搜索关键词" background="#3396FA" @search="onSearch"
        @cancel="onCancel" class="headsearch" />
    </form>

    <!-- 搜索结果 -->
    <search-result v-if="isResultShow" :search-text="searchText" />
    <!-- /搜索结果 -->

    <!-- 联想建议 -->
    <search-suggestion v-else-if="searchText" :search-text="searchText" @search="onSearch" />
    <!-- /联想建议 -->

    <!-- 搜索历史记录 -->
    <search-history v-else :search-histories="searchHistories" @clearHistories="searchHistories = []"
      @search="onSearch" />
    <!-- /搜索历史记录 -->
  </div>
</template>

<script>
import SearchHistory from './components/search-history'
import SearchSuggestion from './components/search-suggestion'
import SearchResult from './components/search-result'
import { setItem, getItem } from '@/utils/storage'
export default {
  name: 'SearchPage',
  data () {
    return {
      searchText: '',
      // 搜索结果显示状态
      isResultShow: false,
      searchHistories: getItem('TOUTIAO_SEARCH_HISTORIES') || [] // 搜索的历史记录数据
    }
  },
  methods: {
    onSearch (val) {
      // 更新文本框内容
      // this.searchText = val

      // 存储搜索历史记录
      // 要求：不要有重复历史记录、最新的排在最前面
      // const index = this.searchHistories.indexOf(val)
      // if (index !== -1) {
      //   this.searchHistories.splice(index, 1)
      // }
      this.searchHistories.unshift(val)
      this.searchHistories = [...new Set(this.searchHistories)]
      this.searchText = val

      // 渲染搜索结果
      this.isResultShow = true
    },

    onCancel () {
      this.$router.back()
    }

  },
  computed: {},
  watch: {
    searchHistories (value) {
      setItem('TOUTIAO_SEARCH_HISTORIES', value)
    }
  },
  filters: {},
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult
  },
  created () { },
  mounted () { }
}
</script>

<style scoped lang='less'>
.search-container {
  .van-search {
    position: sticky;
    top: 0;
  }
  .van-search__action {
    color: #fff;
  }
  /deep/.van-field__left-icon {
    .van-icon-search {
      color: #aaa !important;
    }
  }
}
</style>
